package com.lzy.authorizationServer.config;

import com.lzy.authorizationServer.filter.JwtLoginFilter;
import com.lzy.conf.RsaKeyProperties;
import com.lzy.securityResources.service.impl.SecurityUserImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * description: WebSecurityConfig ()<br>
 * date: 2022-8-13 20:12 <br>
 * author: lcc <br>
 * version: 1.0 <br>
 */
@Configuration
@EnableWebSecurity()
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private SecurityUserImpl securityUser;
    private RsaKeyProperties rsaKeyProperties;

    @Autowired
    public WebSecurityConfig(SecurityUserImpl securityUser, RsaKeyProperties rsaKeyProperties) {
        this.securityUser = securityUser;
        this.rsaKeyProperties = rsaKeyProperties;
    }

    @Value("${jwt.expire}")
    private long expire;

    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据库中
        auth.userDetailsService(securityUser).passwordEncoder(getPasswordEncoder());
    }

    /**
     * 配置SpringSecurity相关信息
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()  //关闭csrf
                .addFilter(new JwtLoginFilter(super.authenticationManager(),rsaKeyProperties,expire))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);    //禁用session
    }
}
